package com.lyh.example.weixin_demo_back.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
// 参考博客
// https://blog.csdn.net/weixin_43668816/article/details/128902019
// https://blog.csdn.net/agonie201218/article/details/135013169
@RestController
@RequestMapping("/esApi")
public class EsController {
    public final static String index = "test3";

    @PutMapping("/addMapping")
    public String addMapping() {
        ElasticsearchClient esClient = getEsClient();
        try {
            Reader reader = getReader();
            ElasticsearchIndicesClient indexClient = esClient.indices();
            PutMappingResponse putMappingResponse = indexClient.putMapping(request -> request.index(index).withJson(reader));
            boolean acknowledged = putMappingResponse.acknowledged();
            if(acknowledged){
                System.out.println("索引mapping【" + index + "】已存在！");
            }else{
                System.out.println("索引mapping添加成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

    private static Reader getReader() {
        String jsonMapping = """
                {
                  "properties": {
                    "name": {
                      "type": "text"
                    },
                    "age": {
                      "type": "text"
                    },
                    "gender": {
                      "type": "text"
                    }
                  }
                }
                """;
        Reader reader = new StringReader(jsonMapping);
        return reader;
    }

    @PutMapping("/createIndex")
    public String createIndex() throws IOException {
        //创建索引
        ElasticsearchClient esClient = getEsClient();
        Map<String, Property> map = new HashMap<>(20);
        // 获取【索引客户端对象】
        ElasticsearchIndicesClient indexClient = esClient.indices();
////        // 1、构建【存在请求对象】
        ExistsRequest existsRequest = new ExistsRequest.Builder().index(index).build();
//
//        // 2、判断目标索引是否存在
        boolean flag = indexClient.exists(existsRequest).value();
        if (flag) {
            // 目标索引已存在
            System.out.println("索引【" + index + "】已存在！");
        } else {
            // 1. 获取【创建索引请求对象】
            CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index).mappings(TypeMapping.of(builder ->
                builder.withJson(getReader()))).build();
            // 2. 创建索引，得到【创建索引响应对象】
            CreateIndexResponse createIndexResponse = indexClient.create(createIndexRequest);
//            createIndexResponse = indexClient.create(req -> req.index(index));
            // System.out.println("创建索引响应对象：" + createIndexResponse);
            boolean result = createIndexResponse.acknowledged();
            if (result) {
                System.out.println("索引【" + index + "】创建成功！");
            } else {
                System.out.println("索引【" + index + "】创建失败！");
            }
        }

//
//        esClient.indices().putMapping(PutMappingRequest.of(mapping->mapping
//                .properties(map)
//                .index(index)
//        ));

//        String indexName = index;
//        String jsonMapping = """
//                {
//                  "properties": {
//                    "field1": {
//                      "type": "text"
//                    },
//                    "field2": {
//                      "type": "keyword"
//                    },
//                    "field3": {
//                      "type": "date"
//                    }
//                  }
//                }
//                """;
        return "ok";
    }

    private ElasticsearchClient getEsClient() {
        // URL and API key
        String serverUrl = "http://localhost:9200";
        // Create the low-level client
        RestClient restClient = RestClient
                .builder(HttpHost.create(serverUrl))
                .build();

        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // And create the API client
        ElasticsearchClient elasticsearchClient = new ElasticsearchClient(transport);
        return elasticsearchClient;
    }

}
